﻿using System;
using GalaSoft.MvvmLight.Messaging;

namespace WebberCross.Obelisk.MvvmLightDemo.Navigation
{
  public class MessageReceiver<T> where T : InitMessageBase
  {
    private Action<T> _handler = null;
    private T _message = null;

    public MessageReceiver(Action<T> handler)
    {
      this._handler = handler;

      // Wait for messages
      Messenger.Default.Register<T>(this, message =>
      {
        if (this._message != null && this._message != message)
        {
          message.Received = true;

          this.OnMessageReceived(message);
        }
      });
    }

    /// <summary>
    /// Send empty message on instantiation
    /// </summary>
    /// <param name="message"></param>
    public MessageReceiver(Action<T> handler, bool sendInitMessage)
      : this(handler)
    {
      if (sendInitMessage)
      {        this._message = Activator.CreateInstance(typeof(T)) as T;

        // Send empty message
        Messenger.Default.Send<T>(this._message);
      }
    }

    private void OnMessageReceived(T message)
    {
      if (this._handler != null)
        this._handler(message);
    }
  }
}
